
package com.gp.activity.detail;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPlanNode;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.RouteOverlay;
import com.baidu.mapapi.TransitOverlay;
import com.gp.R;
import com.gp.adapter.MenuGridViewAdapter;
import com.gp.controls.AddOverlay;
import com.gp.model.MenuItem;

public class SightMapActivity extends MapActivity {

    // 底部菜单
    private GridView mGridView;
   //加载框
    private ProgressDialog mProgress;
    
    // 记录当前位置坐标，景点位置坐标
    private GeoPoint mMyGeoPoint, mSightGeoPoint;

    // 记录当前路线结点信息,景点路线结点信息
    private MKPlanNode mMyNode, mSightNode;

    // 地图上当前位置的覆盖物,景点位置的覆盖物
    Drawable mMyLocmarker, mSightLocmarker;

    // 地图View
    static MapView mMapView;

    // 搜索模块，也可去掉地图模块独立使用
    private MKSearch mSearch;

    // create时注册此listener，Destroy时需要Remove
    private LocationListener mLocationListener;

    // 地图引擎
    private BMapManager mapManager;

    // 地图密钥
    private String key = "792030142E0D7C8500D818FF0929DDEB98BD93C2";
    // 坐标数组的下标
    private int location;
    // 因为intent传GeoPoint对象有点麻烦，我把经纬度放在这里，传过来的是下标
    private static GeoPoint[] locationPoints = {
            new GeoPoint(25588845, 110682189),
            new GeoPoint(25276597, 110302879),
            new GeoPoint(25113939, 110461753),
            new GeoPoint(25273362, 110302421),
            new GeoPoint(24815511, 110406633),
            new GeoPoint(25730532, 110078303),
            new GeoPoint(24647818, 110446096),
            new GeoPoint(24725194, 110476531), };

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.sightmap);

        initMapManager();
        initView();
        initListener();
        getMylocation();
        getData();
    }
@Override
protected void onStart() {
    showProgress();
    super.onStart();
}
    private void getData() {
        // 用Bundle来接受数据
        Bundle qBundle = getIntent().getExtras();
        location = qBundle.getInt("location");
    }

    /**
     * @Title: initMapManager
     * @param
     * @return void
     * @throws
     * @date Aug 4, 2013 9:00:55 PM
     * @version 1.0
     * @Description: 初始化地图的引擎
     */
    private void initMapManager() {

        mapManager = new BMapManager(getApplication());
        mapManager.init(key, null);
        mapManager.start();
        super.initMapActivity(mapManager);
    }

    private List<MenuItem> initValue() {

        int imaID[] = { R.drawable.selfguide_map_bus,
                R.drawable.selfguide_map_drive, R.drawable.selfguide_map_walk,
                R.drawable.selfguide_map_sight, };
        String name[] = {"公交","自驾","步行","景点"};

        List<MenuItem>  menuItems = new ArrayList<MenuItem>();

        for (int i = 0; i < imaID.length; i++) {
            MenuItem qMenuItem = new MenuItem(imaID[i], name[i]);

            menuItems.add(qMenuItem);
        }

        return menuItems;
    }

    /**
     * @Title: initView
     * @param
     * @return void
     * @throws
     * @date Aug 4, 2013 9:01:21 PM
     * @version 1.0
     * @Description: 初始化控件
     */
    private void initView() {

        mMapView = (MapView) findViewById(R.id.bmapView);
        // 设置启用内置的缩放控件
        mMapView.setBuiltInZoomControls(true);
        // 设置缩放级别
        mMapView.getController().setZoom(16);

        // 得到需要标在地图上的资源
        mMyLocmarker = getResources().getDrawable(
                R.drawable.selfguide_map_me_boo);
        // 为maker定义位置和边界
        mMyLocmarker.setBounds(0, 0, mMyLocmarker.getIntrinsicWidth(),
                mMyLocmarker.getIntrinsicHeight());

        // 得到需要标在地图上的资源
        mSightLocmarker = getResources().getDrawable(
                R.drawable.selfguide_map_sight_boo);
        // 为maker定义位置和边界
        mSightLocmarker.setBounds(0, 0, mMyLocmarker.getIntrinsicWidth(),
                mMyLocmarker.getIntrinsicHeight());
        
        
        
        // 底部菜单
        mGridView = (GridView) findViewById(R.id.GridView_toolbar);
        mGridView.setSelector(R.drawable.menu_select_down);
        mGridView.setAdapter(new MenuGridViewAdapter(this,initValue()));
    }

    /**
     * @Title: getSightlocation
     * @param
     * @return void
     * @throws
     * @date Aug 4, 2013 9:01:38 PM
     * @version 1.0
     * @Description: 得到景点的位置
     */
    private void getSightlocation() {

        // 根据地址名获取地址信息 异步函数，返回结果在MKSearchListener里的onGetAddrResult方法通知
        mSightGeoPoint = locationPoints[location];
        mSightNode = new MKPlanNode();
        mSightNode.pt = mSightGeoPoint;
        mSearch.reverseGeocode(mSightGeoPoint);

    }

    /**
     * @Title: getDrivingLine
     * @param
     * @return void
     * @throws
     * @date Aug 4, 2013 9:02:08 PM
     * @version 1.0
     * @Description: 得到驾车路线
     */
    private void getDrivingLine() {

        // 驾车路线搜索，返回结果在MKSearchListener里的onGetDrivingRouteResult方法通知
        // 参数依次为：起始点所在城市，起始点坐标，终点所在城市，终点坐标
        mSearch.drivingSearch("桂林", mMyNode, "桂林", mSightNode);
    }

    /*
     * @Title: getBusLine
     * 
     * @param
     * 
     * @return void
     * 
     * @throws
     * 
     * @date Aug 4, 2013 9:02:33 PM
     * 
     * @version 1.0
     * 
     * @Description: 公交路线
     */
    private void getBusLine() {

        // 公交路线搜索.返回结果在MKSearchListener里的onGetTransitRouteResult方法通知
        mSearch.transitSearch("桂林", mMyNode, mSightNode);

    }

    /**
     * @Title: getWalkingLine
     * @param
     * @return void
     * @throws
     * @date Aug 4, 2013 9:02:45 PM
     * @version 1.0
     * @Description: 步行路线
     */
    private void getWalkingLine() {

        // 步行路线搜索,返回结果在MKSearchListener里的onGetWalkingRouteResult方法通知
        mSearch.walkingSearch("桂林", mMyNode, "桂林", mSightNode);
    }

    /**
     * @Title: getMylocation
     * @param
     * @return void
     * @throws
     * @date Aug 4, 2013 9:02:58 PM
     * @version 1.0
     * @Description: 自己的位置
     */
    private void getMylocation() {

        Log.v("shijunxing", "meed");

        // 设定GPS的响应
        mLocationListener = new LocationListener() {

            public void onLocationChanged(Location location) {

                if (location != null) {

                    // 得到当前位置
                    mMyGeoPoint = new GeoPoint(
                            (int) (location.getLatitude() * 1E6),
                            (int) (location.getLongitude() * 1E6));
                    // 给当前位置节点赋值
                    mMyNode = new MKPlanNode();
                    mMyNode.pt = mMyGeoPoint;

                    // 对以给定的点GeoPoint，开始动画显示地图
                    SightMapActivity.mMapView.getController().animateTo(
                            mMyGeoPoint);

                    // 清空mMapView里的层
                    SightMapActivity.mMapView.getOverlays().clear();
                    // 添加一个图层
                   boolean isLoad =  SightMapActivity.mMapView.getOverlays().add(
                            new AddOverlay(mMyLocmarker, SightMapActivity.this,
                                    mMyGeoPoint, null));
      
                   if (isLoad) {
                              stopProgress();
                          }
                    // 显示经纬度信息在地图下方
                    Toast.makeText(SightMapActivity.this, "当前所在位置",
                            Toast.LENGTH_LONG).show();

                }

            }
        };

    }

    /**
     * @Title: initSearchListener
     * @param
     * @return void
     * @throws
     * @date Aug 4, 2013 9:03:15 PM
     * @version 1.0
     * @Description: 初始化搜素模块，对各个搜索函数进行监听
     */
    private void initListener() {

        // 初始化底部菜单监听

        mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                switch (arg2) {
                    case 0:
                        getBusLine();
                        break;
                    case 1:
                        getDrivingLine();
                        break;
                    case 2:
                        getWalkingLine();
                        break;
                    case 3:
                        getSightlocation();
                        break;

                    default:
                        break;
                }
                
                

            }
        });

        // 初始化地图监听
        mSearch = new MKSearch();
        mSearch.init(mapManager, new MKSearchListener() {

            // 返回walkingSearch（）的结果，并作出处理
            @Override
            public void onGetWalkingRouteResult(MKWalkingRouteResult res,
                    int error) {
                // 错误号可参考MKEvent中的定义
                if (error != 0 || res == null) {
                    Toast.makeText(SightMapActivity.this, "抱歉，未找到结果",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                RouteOverlay routeOverlay = new RouteOverlay(
                        SightMapActivity.this, mMapView);
                // 此处仅展示一个方案作为示例
                routeOverlay.setData(res.getPlan(0).getRoute(0));
                mMapView.getOverlays().clear();
                mMapView.getOverlays().add(routeOverlay);
                mMapView.invalidate();
                mMapView.getController().animateTo(res.getStart().pt);

            }

            // 返回transitSearch（）的结果，并作出处理
            @Override
            public void onGetTransitRouteResult(MKTransitRouteResult res,
                    int error) {
                if (error != 0 || res == null) {
                    Toast.makeText(SightMapActivity.this, "抱歉，未找到结果",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                TransitOverlay routeOverlay = new TransitOverlay(
                        SightMapActivity.this, mMapView);

                // 此处仅展示一个方案作为示例
                routeOverlay.setData(res.getPlan(0));
                mMapView.getOverlays().clear();
                mMapView.getOverlays().add(routeOverlay);
                mMapView.invalidate();

                mMapView.getController().animateTo(res.getStart().pt);
            }

            // 返回drivingSearch（）的结果，并作出处理
            @Override
            public void onGetDrivingRouteResult(MKDrivingRouteResult res,
                    int error) {

                if (error != 0 || res == null) {
                    Toast.makeText(SightMapActivity.this, "抱歉，未找到结果",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                RouteOverlay routeOverlay = new RouteOverlay(
                        SightMapActivity.this, mMapView);
                // 此处仅展示一个方案作为示例
                routeOverlay.setData(res.getPlan(0).getRoute(0));
                mMapView.getOverlays().clear();
                mMapView.getOverlays().add(routeOverlay);
                mMapView.invalidate();
                mMapView.getController().animateTo(res.getStart().pt);

            }

            // 返回地址信息搜索结果
            @Override
            public void onGetAddrResult(MKAddrInfo res, int error) {
                if (error != 0) {
                    String str = String.format("错误号：%d", error);
                    Toast.makeText(SightMapActivity.this, str,
                            Toast.LENGTH_LONG).show();
                    return;
                }

                // 将景点在地图上画出
                mMapView.getController().animateTo(res.geoPt);
                // 标出景点位置
                mMapView.getOverlays().add(
                        new AddOverlay(mSightLocmarker, SightMapActivity.this,
                                res.geoPt, res.strAddr));

            }

            @Override
            public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {

            }

            @Override
            public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {

            }

            @Override
            public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {

            }
        });

    }

    // 在生命周期函数里管理地图引擎
    @Override
    protected void onPause() {
        if (mapManager != null) {
            // 注销搜素监听
            mapManager.getLocationManager().removeUpdates(mLocationListener);
            mapManager.stop();

        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapManager.getLocationManager().requestLocationUpdates(
                mLocationListener);
        mapManager.start();
        super.onResume();
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

    
    
    private void showProgress() {
        mProgress = ProgressDialog.show(this, "", "加载地图...");
    }
    
    private void stopProgress() {
        mProgress.cancel();
    }
}
